package com.project;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.project.facebook.SessionStore;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

// TODO: Auto-generated Javadoc
/**
 * The Class Preview.
 */
public class Preview extends Activity {
	
	/** The db help. */
	private DBHelper dbHelp;
	
	private Intent intent;
	
	/** The show name. */
	private TextView showName;
	
	/** The show des. */
	private TextView showDes;

	/** The bundle. */
	private Bundle bundle;
	
	/** The name text. */
	private String nameText = "";
	
	/** The des text. */
	private String desText = "";

	/** The Constant IMAGE_URI. */
	public final static String IMAGE_URI = "Preview.imageURL";
	
	/** The Constant NAME. */
	public final static String NAME = "Preview.name";
	
	/** The Constant DESCRIPTION. */
	public final static String DESCRIPTION = "Preview.description";

	/** The uri. */
	private Uri uri;
	
	/** The location manager. */
	private LocationManager locationManager;
	
	/** The image view. */
	private ImageView imageView;
	
	/** The vtbtn fb. */
	private ToggleButton vtbtnFb;
	
	/** The pin button. */
	private Button pinButton;
	
	/** The m intent. */
	private Intent mIntent;

	/** The geo lng. */
	private Double geoLat, geoLng;
	
	/** The m progress dialog. */
	private ProgressDialog mProgressDialog;
	
	/** The m facebook. */
	private Facebook mFacebook;
	
	/** The m facebook runner. */
	private AsyncFacebookRunner mFacebookRunner;

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.preview);

		init();
		initData();
	}

	/**
	 * Inits the.
	 */
	private void init() {
		dbHelp = new DBHelper(this);

		imageView = (ImageView) findViewById(R.id.processImage);
		imageView.setMaxWidth(200);
		showName = (TextView) findViewById(R.id.showName);
		showDes = (TextView) findViewById(R.id.showDes);
		vtbtnFb = (ToggleButton) findViewById(R.id.tbtn_share_fb);

		vtbtnFb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				mFacebook = new Facebook(ProjectActivity.APP_ID);
				if (SessionStore.restore(mFacebook, Preview.this)) {
					if (arg1) {
						Toast.makeText(Preview.this, "Shared to Facebook : ON",
								Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(Preview.this,
								"Shared to Facebook : OFF", Toast.LENGTH_LONG)
								.show();
					}
				} else {
					Toast.makeText(Preview.this, "You not login Facebook.",
							Toast.LENGTH_LONG).show();
					vtbtnFb.setChecked(false);
				}

			}
		});
		pinButton = (Button) findViewById(R.id.pinButton);
		pinButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mPin();
			}
		});

	}

	/**
	 * Inits the data.
	 */
	private void initData() {
		intent = getIntent();

		try {
			File file = new File(intent.getStringExtra(IMAGE_URI));
			uri = Uri.fromFile(file);
			imageView.setImageURI(uri);
		} catch (Exception ex) {
			Toast.makeText(this, intent.getStringExtra(IMAGE_URI),
					Toast.LENGTH_LONG).show();
		}

		Toast.makeText(this, intent.getStringExtra(IMAGE_URI),
				Toast.LENGTH_LONG).show();

		// setName

		bundle = this.getIntent().getExtras();
		nameText = bundle.getString("name");
		desText = bundle.getString("description");

		showName.setText("Name Location : " + nameText);
		showName.setPadding(5, 10, 5, 10);
		showDes.setText("Description : " + desText);
		showDes.setPadding(5, 0, 5, 10);

		String context = Context.LOCATION_SERVICE;
		locationManager = (LocationManager) getSystemService(context);

		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);

		String provider = locationManager.getBestProvider(criteria, true);
		Location location = locationManager.getLastKnownLocation(provider);
		if (location != null) {
			geoLat = location.getLatitude() * 1E6;
			geoLng = location.getLongitude() * 1E6;
		}
	}

	/**
	 * M pin.
	 */
	private void mPin() {
		mPinToDB();
		if (vtbtnFb.isChecked()) {
			mPostFacebook();
		}
	}

	/**
	 * M pin to db.
	 */
	private void mPinToDB() {
		dbHelp = new DBHelper(Preview.this);
		Bundle bundle = new Bundle();
		try {
			dbHelp.AddPin(nameText, geoLat, geoLng, desText, intent.getStringExtra(IMAGE_URI));
			mIntent = new Intent(Preview.this, MapView.class);
			Cursor cur = dbHelp.lastInsert();
			while (cur.moveToNext()) {
				bundle.putInt("id",
						cur.getInt(cur.getColumnIndex(DBHelper.colID)));
				mIntent.putExtras(bundle);
			}
			if (!vtbtnFb.isChecked()) {
				startActivity(mIntent);
			}
		} catch (Exception e) {
			Toast.makeText(Preview.this, "error", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * M post facebook.
	 */
	private void mPostFacebook() {
		Bundle params = new Bundle();
		params.putString("message", nameText + " " + desText);
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inTempStorage = new byte[1 * 1024 * 1024]; // Max Image size. <=================
		Bitmap bmp = BitmapFactory.decodeFile(uri.getPath(), options);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);

		params.putByteArray("picture", baos.toByteArray());

		mFacebook = new Facebook(ProjectActivity.APP_ID);
		SessionStore.restore(mFacebook, Preview.this);
		mProgressDialog = ProgressDialog.show(this, "",
				"Posting to facebook...");
		mFacebookRunner = new AsyncFacebookRunner(mFacebook);
		mFacebookRunner.request("me/photos", params, "POST",
				new RequestListener() {
					public void onComplete(String response, Object state) {
						Log.e("TAG", response);
						mProgressDialog.dismiss();
						startActivity(mIntent);
					}

					public void onIOException(final IOException e, Object state) {
						Log.e("TAG", e.toString());
						runOnUiThread(new Runnable() {

							public void run() {
								mProgressDialog.dismiss();
								Toast.makeText(Preview.this, e.toString(),
										Toast.LENGTH_SHORT);

							}
						});
					}

					public void onFileNotFoundException(
							final FileNotFoundException e, Object state) {
						Log.e("TAG", e.toString());
						runOnUiThread(new Runnable() {

							public void run() {
								mProgressDialog.dismiss();
								Toast.makeText(Preview.this, e.toString(),
										Toast.LENGTH_SHORT);

							}
						});
					}

					public void onMalformedURLException(
							final MalformedURLException e, Object state) {
						Log.e("TAG", e.toString());
						runOnUiThread(new Runnable() {

							public void run() {
								mProgressDialog.dismiss();
								Toast.makeText(Preview.this, "Post Complate",
										Toast.LENGTH_SHORT);

							}
						});
					}

					public void onFacebookError(final FacebookError e,
							Object state) {
						Log.e("TAG", e.toString());
						runOnUiThread(new Runnable() {

							public void run() {
								mProgressDialog.dismiss();
								Toast.makeText(Preview.this, e.toString(),
										Toast.LENGTH_SHORT);

							}
						});
					}
				}, null);
	}
}
